package cn.xaut.二叉树;

import cn.xaut.剑指offer.m20.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 101. 对称二叉树
 */
public class demo101 {

    // 递归解法
    public boolean isSymmetric(TreeNode root) {
        if (root == null)
            return true;
        return check(root.left, root.right);
    }

    private boolean check(TreeNode left, TreeNode right) {
        
        // 递归终止条件
        if (left == null && right == null)
            return true;
        if (left == null || right == null)
            return false;

        // 递归过程
        return left.val == right.val && check(left.left, right.right) && check(left.right, right.left);
    }
    
    // 非递归解法
    public boolean isSymmetric2(TreeNode root) {

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        queue.add(root);

        while (!queue.isEmpty()) {
            TreeNode t1 = queue.poll();
            TreeNode t2 = queue.poll();
            if (t1 == null && t2 == null)
                continue;
            if (t1 == null || t2 == null)
                return false;
            if (t1.val != t2.val)
                return false;
            queue.add(t1.left);
            queue.add(t2.right);
            queue.add(t1.right);
            queue.add(t2.left);
        }
        return true;
    }
}
